package com.ssrs.framework.web.config;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.alibaba.ttl.threadpool.TtlExecutors;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.lang.reflect.Method;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 异步线程池
 * @author ssrs
 */
@Configuration
@EnableAsync
public class NativeAsyncTaskExecutePoolConfig implements AsyncConfigurer {
    private static final Log log = LogFactory.get(ThreadPoolConfig.class);

    @Autowired
    private ThreadPoolConfig poolConfig;

    @Bean
    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();

        // 核心线程数
        executor.setCorePoolSize(poolConfig.getCorePoolSize());

        // 最大支持线程数
        executor.setMaxPoolSize(poolConfig.getMaxPoolSize());

        //线程名字前缀
        executor.setThreadNamePrefix("AsyncExecutor-");

        executor.setMaxPoolSize(poolConfig.getMaxPoolSize());
        executor.setQueueCapacity(poolConfig.getQueueCapacity());
        executor.setKeepAliveSeconds(poolConfig.getKeepAliveSeconds());

        // 线程池对拒绝任务(无线程可用)的处理策略
        // setRejectedExecutionHandler：当pool已经达到max size的时候，如何处理新任务
        // CallerRunsPolicy：不在新线程中执行任务，而是由调用者所在的线程来执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();

        log.info("异步线程池-核心线程数定义为[" + executor.getCorePoolSize() + "], 最大支持的线程数量为[" + executor.getMaxPoolSize() + "], 线程池维护线程所允许的空闲时间[" + executor.getKeepAliveSeconds() + "].");

        // 重点：使用 TTL 提供的 TtlExecutors
        return TtlExecutors.getTtlExecutor(executor);
    }

    /**
     * 异步任务中异常处理
     *
     * @return
     */
    @Bean
    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new AsyncUncaughtExceptionHandler() {

            @Override
            public void handleUncaughtException(Throwable arg0, Method arg1, Object... arg2) {
                log.error("==========================" + arg0.getMessage() + "=======================", arg0);
                log.error("exception method:" + arg1.getName());
            }
        };
    }
}
